<?php
/**
 * 异步任务队列类
 *
 * @author vincent
 *        
 */
class TaskQueue {
	/**
	 * 创建gearman client
	 *
	 * @return GearmanClient
	 */
	private static function getClient() {
		static $client = NULL;
		if ($client == NULL) {
			$client = new GearmanClient ();
			$client->addServer ( Mikasa::getConfig ( 'JOB_SERVER_HOST' ), Mikasa::getConfig ( 'JOB_SERVER_PORT' ) );
		}
		return $client;
	}
	/**
	 * 添加异步任务
	 *
	 * @param string $functionName 函数名
	 * @param string $data 参数
	 */
	public static function addBackGroundTask($functionName, $data = '') {
		$client = self::getClient ();
		return $client->doBackground ( $functionName, serialize ( $data ) );
	}
	
	/**
	 * 开始处理任务
	 */
	public static function run($data) {
		// 判断是否加载gearman扩展
		if (! extension_loaded ( 'gearman' )) {
			throw new Exception ( 'the extension gearman is not loaded!' );
		}
		// 导入任务处理方法
		require SYSTEM_PATH . '/common/tasks.php';
		$config = &$GLOBALS ['CONFIG'];
		$worker = new GearmanWorker ();
		$worker->addServer ( $config ['JOB_SERVER_HOST'], $config ['JOB_SERVER_PORT'] );
		
		foreach ( $data as $key => $value ) {
			$worker->addFunction ( $key, $value );
		}
		
		while ( true ) {
			try {
				$result = $worker->work ();
			}
			catch ( Exception $e ) {
				Logger::log ( 'task', 'exception:' . $e->getTraceAsString () );
			}
		}
	}
}